package com.leetcode.partition1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author `RKC`
 * @date 2021/8/14 11:46
 */
public class LC47全排列2 {

    public static List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> answer = new ArrayList<>();
        Arrays.sort(nums);
        backtracking(answer, new ArrayList<>(), nums, new boolean[nums.length]);
        return answer;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 2};
        System.out.println(permuteUnique(nums));
    }

    private static void backtracking(List<List<Integer>> answer, List<Integer> path, int[] nums, boolean[] used) {
        if (path.size() == nums.length) {
            answer.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            //经过排序后，两个相同的元素是在一起的，如果之前使用过该元素，就没有必要继续使用该元素进行回溯；used[i]剪枝
            if ((i > 0 && nums[i] == nums[i - 1] && used[i - 1]) || used[i]) continue;
            path.add(nums[i]);
            used[i] = true;
            backtracking(answer, path, nums, used);
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
}
